﻿using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using System.Collections.Generic;
using System.Net;
using System.Net.Http;
using System.Net.Http.Formatting;
using System.Web.Http;
using System.Web.Http.Filters;
using WMSNet.Core.Infrastructure.Api;

namespace WMSNet.Core.Infrastructure.Api
{
    public class ExceptionHandlingAttribute : ExceptionFilterAttribute
    {
        public override void OnException(HttpActionExecutedContext context)
        {
            JsonSerializerSettings jsonSerializerSettings = new JsonSerializerSettings();
            jsonSerializerSettings.Converters.Add((JsonConverter)new IsoDateTimeConverter());

            jsonSerializerSettings.NullValueHandling = NullValueHandling.Ignore;
            throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError)
            {
                Content = (HttpContent)new ObjectContent(context.Exception.GetType(), (object)context.Exception, (MediaTypeFormatter)new JsonNetFormatter(jsonSerializerSettings)),
                ReasonPhrase = "Exception"
            });
        }
    }
}
